const rootPath      = '../';
const currentPath   = './'

var config  = require(currentPath + 'config.js');
var Promise = require(rootPath + 'util/promise.js');

// 获取当前位置
function getLocation()
{
    return new Promise((resolve, reject) => {
        wx.getLocation({
            type    : 'wgs84',
            success : (response) => {
                let app = getApp();

                app.globalData.latitude     = response.latitude;
                app.globalData.longitude    = response.longitude;

                resolve(response);
            },
            fail : e => reject(e),
        });
    });
}

// 选取图片
function chooseImage(count = 9, size = ['compressed'], source = ['album', 'camera'])
{
    return new Promise((resolve, reject) => {
        wx.chooseImage({
            count       : count,
            sizeType    : size,
            sourceType  : source,
            success     : res => resolve(res),
            fail        : e => reject(e),
        });
    });
}

// 从 store 里面获取 token
function getAccessTokenSync()
{
    try {
        let token = wx.getStorageSync(config.key.access_token_key);

        return JSON.parse(token);
    } catch (e) {
        return {
            'time' : 0,
        };
    }
}

// 设置 token
function setAccessTokenSync(token)
{
    try {
        wx.setStorageSync(config.key.access_token_key, JSON.stringify(token));

        return true;
    } catch (e) {
        config.log(e);

        return false;
    }
}

// 判断时候授权了
function isAuthorize()
{
    try {
        let token   = getAccessTokenSync();
        let now     = new Date();
        let second  = Math.floor(now.getTime() / 1000);

        return (second <= token.time);
    } catch (e) {
        console.log(e);

        return false;
    }
}

// 获取当前时间到指定时间的差值
function timeLeft(endSecond = 0)
{
    let nowTime     = new Date();
    let nowSecond   = Math.round(nowTime.getTime() / 1000);
    let diffSecond  = endSecond - nowSecond;

    if (diffSecond <= 0) {
        return [0, 0, 0, 0];
    }

    let second      = 1;
    let minute      = 60 * second;
    let hour        = 60 * minute;
    let day         = 24 * hour;

    let leftDays    = Math.floor(diffSecond / day);
    let leftHours   = Math.floor((diffSecond % day) / hour);
    let leftMinutes = Math.floor((diffSecond % hour) / minute);
    let leftSeconds = Math.floor((diffSecond % minute) / second);
    leftSeconds     = leftSeconds < 10 ? "0" + leftSeconds : leftSeconds;

    return [leftDays, leftHours, leftMinutes, leftSeconds];
}

// 导出
exports = module.exports = {
    getAccessTokenSync  : getAccessTokenSync,
    setAccessTokenSync  : setAccessTokenSync,
    isAuthorize         : isAuthorize,
    timeLeft            : timeLeft,
    getLocation         : getLocation,
    chooseImage         : chooseImage,
};
